/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="ORGIntersectionTree">
    <!-- <el-button @click="getCheckedNodes">获取选中的路口</el-button> -->
    <!-- <el-button @click="setCheckedIntersection">设置选中的路口</el-button> -->
    <div class="all-operate">
      <el-button
        v-if="isOpen == false"
        type="text"
        class="all-button"
        icon="el-icon-circle-plus-outline"
        @click="changeTreeNodeStatus"
        >{{ $t("openatc.button.expandall") }}</el-button
      >
      <el-button
        v-else
        type="text"
        class="all-button"
        icon="el-icon-remove-outline"
        @click="changeTreeNodeStatus"
        >{{ $t("openatc.button.collapseall") }}</el-button>
    </div>
    <el-tree
      ref="tree"
      node-key="nodeid"
      :show-checkbox="isOpenCheckbox"
      :class="isOpenCheckbox ? 'checkboxtree' : 'origintree'"
      :render-after-expand="false"
      :data="treeData"
      :props="defaultProps"
      @node-click="handleNodeClick"
      @check="getCheckedIntersection"
    >
      <span
        :class="data.agentid !== undefined ? 'dev-node' : 'org-node'"
        slot-scope="{ node, data }"
      >
        <span v-if="data.agentid !== undefined">
          <svg-icon
            v-if="data.state === 'UP' && data.status === 0"
            icon-class="dev-tree-online"
            className="dev-tree-icon"
          ></svg-icon>
          <svg-icon
            v-if="data.state === 'DOWN'"
            icon-class="dev-tree-offline"
            className="dev-tree-icon"
          ></svg-icon>
        </span>
        <span class="dev-name">
          <el-tooltip
            v-if="node.label && node.label.length > 17"
            placement="bottom-start"
          >
            <div slot="content">{{ node.label }}</div>
            <span class="devname">{{ node.label }}</span>
          </el-tooltip>
          <span v-else>{{ node.label }}</span>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import { GetOrganizationList } from '../../api/organization'
import { getMessageByCode } from '../../utils/responseMessage'
import { elTreeModel } from './treemodel.js'
import { GetAllDevice, getDeviceRange } from '../../api/device'

export default {
  name: 'ORGIntersectionTree',
  data () {
    return {
      treeData: [],
      outOrgDevs: [], // 未关联信号机的设备
      defaultProps: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      isOpen: true
    }
  },
  props: {
    isOpenCheckbox: { // 是否开启checkboxs
      type: Boolean,
      default: false
    },
    devsfilter: { // 路口模糊查询条件
      type: String,
      default: ''
    }
  },
  // watch: {
  //   devsfilter: {
  //     handler: function () {
  //       this.getDeviceRanges()
  //     },
  //     // 深度观察监听
  //     deep: true
  //   }
  // },
  methods: {
    getOrganizationList () {
      // 查询所有
      GetOrganizationList().then(data => {
        if (data.data.code === '401') { // 判断用户是否在其他地方被踢出
          window.location.reload()
          return
        }
        if (data.data.success !== true) {
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.outOrgDevs = []
        this.orgData = data.data.data.map(ele => {
          return {
            ...ele,
            nodetype: 'org',
            nodeid: `org${ele.id}`
          }
        })
        let uniqueCrossOrgArr = this.extractOrganization()
        this.handleIntersectionRelatedOrganization(uniqueCrossOrgArr)
      })
    },
    extractOrganization () {
      // 按照有组织机构的路口，从全部组织机构中提取组织机构信息，按照组织机构接口返回排序
      let result = this.orgData.filter(obj => this.uniqueCrossOrgList.includes(obj.orgnization_code))
      // console.log(result)
      return result
    },
    getAllIntersection () {
      this.listLoading = true
      GetAllDevice().then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (res.data.data) {
          this.crossData = res.data.data.map(cross => {
            return {
              ...cross,
              nodetype: 'cross',
              nodeid: `cross${cross.id}`
            }
          })
          this.getOrganizationList()
        } else {
          this.crossData = []
        }
      })
    },
    handleIntersectionRelatedOrganization (orgData) {
      // 未关联组织机构的路口跟根组织平级
      for (let i = 0; i < this.crossData.length; i++) {
        if (this.crossData[i].code) {
          for (let j = 0; j < orgData.length; j++) {
            if (this.crossData[i].code === orgData[j].orgnization_code) {
              if (!orgData[j].cross) {
                orgData[j].cross = [this.crossData[i]]
              } else {
                orgData[j].cross.push(this.crossData[i])
              }
            }
          }
        } else {
          // 未关联组织机构的设备
          this.outOrgDevs.push(this.crossData[i])
        }
      }
      let orgtree = elTreeModel.CreateTreeByPath(orgData)
      this.treeData = [...orgtree, ...this.outOrgDevs]
      if (this.treeData.length > 0) {
        this.$emit('treeData', this.treeData)
      }
      if (this.isOpenCheckbox) {
        this.$nextTick(() => {
          this.hideLeafOrgNodeCheckbox()
        })
      }
      this.$nextTick(() => {
        this.changeTreeAllNodeStatus(this.$refs.tree.store.root)
        if (!this.isOpen) {
          this.changeTreeOneLevelChildNodeStatus(this.$refs.tree.store.root)
        }
      })
    },
    hideLeafOrgNodeCheckbox () {
      // 隐藏叶节点是组织机构的复选框
      let isLeafElements = document.querySelectorAll('.is-leaf')
      for (let i = 0; i < isLeafElements.length; i++) {
        let siblingElements = isLeafElements[i].parentNode.children
        for (let j = 0; j < siblingElements.length; j++) {
          if (siblingElements[j].className === 'org-node') {
            var previousSibling = siblingElements[j].previousElementSibling
            if (previousSibling && previousSibling.classList.contains('el-checkbox')) {
              previousSibling.style.visibility = 'hidden' // 隐藏复选框
            }
            siblingElements[j].style.marginLeft = '4px'
          }
        }
      }
      this.$emit('finishLoadTree', this.crossData)
    },
    handleNodeClick (data) {
      // 树节点点击
      if (data.nodetype === 'org') return
      if (data.name === '根组织' || data.name === 'Root') return
      console.log(data)
      this.$emit('treeNodeClick', data)
    },
    getCheckedNodes () {
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      let crossNodes = checkedNodes.filter(ele => ele.nodetype !== 'org')
      console.log(crossNodes)
    },
    getCheckedIntersection (curCheckednode, allCheckedNodes) {
      // checkbox状态改变实时触发，获取当前选中的路口
      let checkedNodes = allCheckedNodes.checkedNodes
      let crossNodes = checkedNodes.filter(ele => ele.nodetype !== 'org' && ele.label !== '根组织' && ele.label !== 'Root')
      let crossNodesIDs = crossNodes.map(ele => ele.id)
      let addNewNodeList = [...this.crossNodes]
      let crossNodesIds = this.crossNodes.map(ele => ele.id)
      let curCheckedNodeId = curCheckednode.id
      if (crossNodesIDs.indexOf(curCheckedNodeId) === -1) {
        // 取消勾选
        addNewNodeList = addNewNodeList.filter(ele => ele.id !== curCheckedNodeId)
        this.crossNodes = this.crossNodes.filter(ele => ele.id !== curCheckedNodeId)
      } else {
        if (crossNodesIds.indexOf(curCheckedNodeId) === -1) {
          // 新的node被选中（传进来的node以外的）
          addNewNodeList.push(curCheckednode)
          this.crossNodes.push(curCheckednode)
        }
      }
      console.log(addNewNodeList)
      this.$emit('checkedNodes', addNewNodeList)
    },
    setCheckedIntersection (crossNodes) {
      // 设置当前选中的路口
      this.crossNodes = crossNodes
      console.log(this.crossNodes)
      let crossdatas = crossNodes.map(cross => {
        return {
          ...cross,
          nodetype: 'cross',
          nodeid: `cross${cross.id}`
        }
      })
      this.$refs.tree.setCheckedNodes(crossdatas)
    },
    getDeviceRanges (devsfilter) {
      // 按搜索条件查询路口信息
      let reqData = {
        'pageNum': 1,
        'pageRow': 10000,
        'search': devsfilter,
        'type': '',
        'platform': '',
        'protocol': '',
        'state': '',
        'code': '',
        'control': -1,
        'mode': -1,
        'tags': ''
      }
      let list = []
      return getDeviceRange(reqData).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (res.data.data.content) {
          list = res.data.data.content
        } else {
          list = []
        }
        this.crossData = list.map(cross => {
          return {
            ...cross,
            nodetype: 'cross',
            nodeid: `cross${cross.id}`
          }
        })
        this.crossOrgList = list.filter(cross => cross.code !== undefined).map(cross => cross.code)
        this.uniqueCrossOrgList = [...new Set(this.crossOrgList)]
        // console.log(list)
        // console.log(this.uniqueCrossOrgList)
        this.getOrganizationList()
        return list
      })
    },
    changeTreeNodeStatus () {
      this.isOpen = !this.isOpen
      if (this.isOpen) {
        this.changeTreeAllNodeStatus(this.$refs.tree.store.root)
      } else {
        this.changeTreeOneLevelChildNodeStatus(this.$refs.tree.store.root)
      }
    },
    changeTreeAllNodeStatus (node) {
      // 全部展开
      node.expanded = true
      for (let i = 0; i < node.childNodes.length; i++) {
        // 改变节点的自身expanded状态
        node.childNodes[i].expanded = true
        // 遍历子节点
        if (node.childNodes[i].childNodes.length > 0) {
          this.changeTreeAllNodeStatus(node.childNodes[i])
        }
      }
    },
    changeTreeOneLevelChildNodeStatus (node) {
      // 第一级组织机构展开
      for (let i = 0; i < node.childNodes.length; i++) {
        if (node.childNodes[i].data.name === '根组织' || node.childNodes[i].data.name === 'Root') {
          node.childNodes[i].expanded = true
        }
        if (node.childNodes[i].childNodes.length > 0) {
          for (let j = 0; j < node.childNodes[i].childNodes.length; j++) {
            // 到一级组织机构隐藏
            node.childNodes[i].childNodes[j].expanded = false
          }
        }
      }
    }
  },
  mounted () {
    // this.getAllIntersection()
    // this.getDeviceRanges()
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  .ORGIntersectionTree {
    height: 100%;
    span {
      float: left;
    }
    .dev-tree-icon {
      width: 20PX;
      height: 20PX;
    }
    .dev-name {
      line-height: 20PX;
      .devname {
        max-width: 238PX;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
</style>
<style lang="scss" rel="stylesheet/scss">
.ORGIntersectionTree {
  font-size: 14PX;
  .el-tree-node__content {
      height: 30PX;
    }
}
.ORGIntersectionTree .origintree .el-tree-node__expand-icon.is-leaf {
    display: none;
  }
.ORGIntersectionTree .origintree .el-tree-node .is-leaf + .dev-node {
    margin-left: 5PX;
  }
/* 组织机构节点不显示checkbox */
.ORGIntersectionTree .checkboxtree .el-tree-node .is-leaf + .el-checkbox .el-checkbox__inner {
  display: inline-block;
}
.ORGIntersectionTree .checkboxtree .el-tree-node .is-leaf + .el-checkbox {
  margin-left: 6PX;
}
.ORGIntersectionTree .checkboxtree .el-tree-node .is-leaf.el-tree-node__expand-icon {
  display: none;
}
.ORGIntersectionTree .checkboxtree .el-tree-node .el-checkbox .el-checkbox__inner {
  display: none;
}
</style>
